package org.feiye.studyday28.case3;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class LoginThread extends Thread {
//线程类：一直监听客户请求，一旦有客户请求，立即开启新线程 ，给出响应（之前服务器做的事）
	// 线程构造方法中去绑定客户端的Socket
	private Socket socket;

	public LoginThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	// 接收客户端请求并响应
	public void run() {
		InputStream in = null;
		ObjectInputStream ois = null;
		OutputStream os = null;
		try {
			// 通过socket获得输入流，获得用户的请求
			in = socket.getInputStream();
			ois = new ObjectInputStream(in);
			User user = (User) ois.readObject();
			System.out.println("客户端说：" + user.getUserName() + "," + user.getPassWord());

			InetAddress ia = socket.getInetAddress();// 获得客户端的ip对象
			String hostAddress = ia.getHostAddress();// 获得主机ip地址
			System.out.println("响应客户端的ip地址：" + hostAddress);

			// 给客户端响应
			String reply = "欢迎进入";
			// 通过输出流讲响应发送给客户端
			os = socket.getOutputStream();
			os.write(reply.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			if (os != null)
				try {
					os.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			if (ois != null)
				try {
					ois.close();
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}
